<template>
  <van-overlay
    :custom-style="{ background: 'rgba(0, 0, 0,1)' }"
    :show="show"
    @click="stop"
  >
    <div class="qrcode-container">
      <div id="reader"></div>
    </div>
  </van-overlay>
</template>

<script setup>
import { ref } from "vue";
import { Html5Qrcode } from "html5-qrcode";
let emit = defineEmits(["goBack"]); //getMsessage 将获得的数据给父组件

const show = ref(false);
let html5QrCode = null;

const start = () => {
  if (!html5QrCode) return;

  html5QrCode
    .start(
      { facingMode: "environment" },
      {
        fps: 2,
        qrbox: { width: 300, height: 280 },
      },
      (decodedText) => {
        emit("goBack", decodedText); // 如需返回结果取消注释
        stop();
      }
    )
    .catch((err) => {
      console.error("扫码错误:", err);
      handleScanError(err);
    });
};

const handleScanError = (err) => {
  const errorMap = {
    NotAllowedError: "您需要授予相机访问权限",
    NotFoundError: "这个设备上没有摄像头",
    NotSupportedError: "摄像头访问只支持在安全的上下文中（HTTPS/localhost）",
    NotReadableError: "相机被占用",
    OverconstrainedError: "安装摄像头不合适",
    StreamApiNotSupportedError: "此浏览器不支持流API",
  };

  const errorMsg = errorMap[err.name] || err.message;
  console.warn("扫码错误:", errorMsg);
  // toast(errorMsg) // 如需使用Toast取消注释
};

const getCameras = async () => {
  try {
    show.value = true;
    const devices = await Html5Qrcode.getCameras();
    if (devices?.length) {
      html5QrCode = new Html5Qrcode("reader");
      start();
    }
  } catch (err) {
    console.error("获取摄像头失败:", err);
    html5QrCode = new Html5Qrcode("reader"); // 降级处理
  }
};

const stop = () => {
  show.value = false;
  html5QrCode
    ?.stop()
    .then(() => console.log("扫码已停止"))
    .catch((err) => console.error("停止扫码失败:", err));
};

// 暴露方法给模板（可选）
defineExpose({
  getCameras,
  stop,
});
</script>
<style lang="scss" scoped>
.qrcode-container {
  position: relative;
  width: 100%;
  height: 100vh;

  #reader {
    position: absolute;
    top: 50%;
    left: 0;
    z-index: 1;
    transform: translateY(-50%);
  }
}

// :deep(#qr-shaded-region) {
//   overflow: hidden;
// }

:deep(#qr-shaded-region::after) {
  position: absolute;
  content: "";
  width: 100%;
  top: 0;
  left: 0;
  transform: translateY(-100%);
  height: 50px;
  background: linear-gradient(180deg, rgba(0, 255, 51, 0) 43%, #00ff33 211%);
  border-bottom: 1px solid #00ff33;
  animation: scan-animation 2s linear infinite;
}

@keyframes scan-animation {
  0% {
    top: 0;
  }

  100% {
    top: 100%;
  }
}
</style>
